﻿using System;
using System.Text.RegularExpressions;
using System.Windows;
using YwangHRMSys.DAL;
using YwangHRMSys.Model;


namespace YwangHRMSys.UI.EmployeeMgr
    {
        /// <summary>
        ///     EmployeeWindowEdit.xaml 的交互逻辑
        /// </summary>
        public partial class EmployeeWindowEdit : Window
            {

                public EmployeeWindowEdit()
                {
                    InitializeComponent();
                }

                public bool IsInsert { get; set; }

                public Guid EditGuid { get; set; }
                /// <summary>
                ///     类别等信息的加载
                /// </summary>
                private void GetByCategory()
                {
                    CmbSex.ItemsSource = new CategoryDAL().GetByCategory("性别");
                    CmbMaritalStatus.ItemsSource = new CategoryDAL().GetByCategory("婚姻状况");
                    CmbPoliticalAffiliation.ItemsSource = new CategoryDAL().GetByCategory("政治面貌");
                    CmbEducation.ItemsSource = new CategoryDAL().GetByCategory("学历");
                    CmbPost.ItemsSource = new CategoryDAL().GetByCategory("职位");
                    CmbJobTitle.ItemsSource = new CategoryDAL().GetByCategory("职称");
                }

                /// <summary>
                ///     加载部门列表
                /// </summary>
                private void DepartmentList()
                {
                    CmbDepartment.ItemsSource = new DepartmentInfoDAL().ListAll();
                }

                /// <summary>
                ///     加载省市列表
                /// </summary>
                private void AreaFullList()
                {
                    DomicilebProvList.ItemsSource = new AreaFullInfoDAL().ListProvAll();
                    NowProvList.ItemsSource = new AreaFullInfoDAL().ListProvAll();
                }

            /// <summary>
            /// 加载民族
            /// </summary>
                private void NationalitiesList()
                {
                    CmbNation.ItemsSource = new NationalitiesInfoDAL().ListAll();
                }
                private void Window_Loaded( object sender, RoutedEventArgs e )
                {          //性别、类别等信息的载入
                    GetByCategory();
                    //加载部门列表
                    DepartmentList();
                    //加载省市信息
                    AreaFullList();
                    //加载民族列表
                    NationalitiesList();

                    if (IsInsert)
                        {
                     
                    DateEntryTime.SelectedDate = DateTime.Now;
                        }
                    else
                    {
                        #region 编辑载入
                     
                        //     CmbJobTitle.Text = "设计师";
                            EmployeeInfoModel employeeModel= new EmployeeInfoDAL().GetById(EditGuid);
                            TxtName.Text = employeeModel.Name;
                            TxtIdCards.Text = employeeModel.IdCard;
                            TxtAge.Text = employeeModel.Age;
                            DateBirthDay.SelectedDate = employeeModel.DateOfBirth;
                            TxtTelephone.Text = employeeModel.TelePhone;
                            TxtEmergencyContact.Text = employeeModel.EmergencyContact;
                            TxtEmergencyContactPhone.Text = employeeModel.EmergencyContactPhone;
                            CmbNation.Text = employeeModel.Nationalities;
                            TxtFileNo.Text = employeeModel.FileNo;
                            TxtEmail.Text = employeeModel.Email;
                            TxtRemarks.Text = employeeModel.Remark;
                        //性别、部门、学历等信息的加载
                            Guid gender = employeeModel.Gender;
                            Guid education = employeeModel.EducationId;
                            Guid departmentid = employeeModel.DepartmentId;
                            Guid post = employeeModel.Post;
                            Guid politicalAffiliationId = employeeModel.PoliticalAffiliationId;
                            Guid jobTitleId = employeeModel.JobTitleId;
                            Guid maritalStatusId = employeeModel.MaritalStatusId;
                            CategoryModel cmbSexModel = new CategoryDAL().GetById(gender);
                            CategoryModel educationModel = new CategoryDAL().GetById(education);
                            CategoryModel postModel = new CategoryDAL().GetById(post);
                            CategoryModel politicalAffiliationIdSexModel = new CategoryDAL().GetById(politicalAffiliationId);
                            CategoryModel jobTitleIdModel = new CategoryDAL().GetById(jobTitleId);
                            CategoryModel maritalStatusIdModel = new CategoryDAL().GetById(maritalStatusId);
                            CmbSex.Text = cmbSexModel.Name;
                            CmbEducation.Text = educationModel.Name;
                            CmbPost.Text = postModel.Name;
                            CmbPoliticalAffiliation.Text = politicalAffiliationIdSexModel.Name;
                            CmbJobTitle.Text = jobTitleIdModel.Name;
                            CmbMaritalStatus.Text = maritalStatusIdModel.Name;
                        //部门列表
                            DepartmentInfoModel departmentidModel = new DepartmentInfoDAL().GetByDepartmentInfoID(departmentid);
                            CmbDepartment.Text = departmentidModel.DepartmentName;
                            //试用期
                            Guid trailDaysId = employeeModel.TrailDaysId;
                            TrailDaysInfoModel trailDaysModel = new TrailDaysInfoDAL().GetByTrailDaysInfoID(trailDaysId);
                            DateEntryTime.SelectedDate = trailDaysModel.DateEntryTime;
                            DatePositiveTime.SelectedDate = trailDaysModel.DatePositiveTime;
                            LabelTrailDays.Text = trailDaysModel.TrailDays;
                          //  TxtRemarks.Text = trailDaysModel.DateEntryTime+"\n" + trailDaysModel.DatePositiveTime;
                            //地址修改
                            Guid domicileAddressIdGuid = employeeModel.DomicileAddressId;
                            Guid currentAddressIdGuid = employeeModel.CurrentAddressId;
                            EmployeeAddressInfoModel addressModel =
                                    new EmployeeAddressInfoDAL().GetByEmployeeAddressInfoId(domicileAddressIdGuid);
                            DomicilebProvList.Text = addressModel.Provinces;
                            DomicileCityList.Text = addressModel.City;
                            DomicileCountyList.Text = addressModel.County;
                        TxtDomicile.Text = addressModel.Address;
                            EmployeeAddressInfoModel currentAddressModel =
                                    new EmployeeAddressInfoDAL().GetByEmployeeAddressInfoId(currentAddressIdGuid);
                            NowProvList.Text = currentAddressModel.Provinces;
                            NowCityList.Text = currentAddressModel.City;
                            NowCountyList.Text = currentAddressModel.County;
                        TxtCurrentAddress.Text = currentAddressModel.Address;
                        //     TxtRemarks.Text = gender.ToString();  

                        #endregion
                    }
                           

                 


                }

                #region 当失去文本框焦点的时候，判断是否满足18位的身份证号码

                //身份证计算方法：
                //            string no="123456789012345678";//身份证号
                //string year = no.Substring(7,4)  //得到年份
                //string month = no.Substring(11,2) //得到月份
                //string day = no.Substring(12,2)  //得到日期
                //    string PeopleNum = "420881198303246579";	//身份证号码
                //    string Sub_str = PeopleNum.Substring(6,8).Insert(4,"-").Insert(7,"-");	//提取出生年份
                //            TimeSpan ts = DateTime.Now.Subtract(Convert.ToDateTime(Sub_str));
                //            Console.WriteLine(ts.Days/365);		//结果输出:28
                    
                /// <summary>
                ///     当失去文本框焦点的时候，判断是否满足18位的身份证号码
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void TxtIdCards_LostFocus( object sender, RoutedEventArgs e )
                {
                    string idcards = TxtIdCards.Text;
                    //C#验证身份证号码-----正则表达式的使用  
                    var r = new Regex
                            (
                            @"(^[1-9][0-9]{5}((19[0-9]{2})|(200[0-9])|2011)(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])[0-9]{3}[0-9xX]$)");

                    //@"(^[1-9][0-9]{5}((19[0-9]{2})|(200[0-9])|2011)(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])[0-9]{3}[0-9xX]$)"
                    bool isMatch = r.IsMatch(idcards);
                    if (isMatch)
                        {
                            if (idcards.Trim()
                                       .Length == 18)
                                {

                                    string idyear = idcards.Substring(6, 4); //从第7位往后面数4位。
                                    string idmonth = idcards.Substring(10, 2);
                                    string idday = idcards.Substring(12, 2);
                                    string iddate = ( idyear + "-" + idmonth + "-" + idday );
                                    DateBirthDay.Text = iddate;

                                    int dateyearNow = DateTime.Now.Year;
                                    int age = dateyearNow - Convert.ToInt32(idyear);

                                    TxtAge.Text = age + "岁";
                                    //1983/04/23
                                    // MessageBox.Show("正确。。");
                                }
                            else
                                {
                                    MessageBox.Show("身份证号不满18位，请检查");
                                    TxtIdCards.Clear();

                                }
                        }
                    else
                        {
                            MessageBox.Show("不是有效的18位身份证号码，请检查格式");
                        }


                }

                #endregion

                #region 

                #endregion

  

         

                private void BtnSave_Click(object sender, RoutedEventArgs e)
                {

                    #region 添加
                    if (IsInsert)
                    {
                        #region   将文本框中的值传输到model中

                        Guid employeeId = Guid.NewGuid();
                        Guid addressDomicileId = Guid.NewGuid();
                        Guid addressNowId = Guid.NewGuid();
                        var employee = new EmployeeInfoModel();
                        employee.Id = employeeId;
                        employee.Name = TxtName.Text;
                        employee.Gender = (Guid)CmbSex.SelectedValue;
                        employee.IdCard = TxtIdCards.Text;
                        employee.EducationId = (Guid)CmbEducation.SelectedValue;
                        employee.DepartmentId = (Guid)CmbDepartment.SelectedValue;
                        employee.Post = (Guid)CmbPost.SelectedValue;
                        employee.PoliticalAffiliationId = (Guid)CmbPoliticalAffiliation.SelectedValue;
                        employee.Age = TxtAge.Text;
                        employee.TelePhone = TxtTelephone.Text;
                        employee.EmergencyContact = TxtEmergencyContact.Text;
                        employee.EmergencyContactPhone = TxtEmergencyContactPhone.Text;
                        employee.Nationalities = CmbNation.Text;
                        employee.MaritalStatusId = (Guid)CmbMaritalStatus.SelectedValue;
                        employee.FileNo = TxtFileNo.Text;
                        employee.Email = TxtEmail.Text;
                        employee.Remark = TxtRemarks.Text;
                        employee.TrailDaysId = employeeId;
                        employee.DomicileAddressId = addressDomicileId;
                        employee.CurrentAddressId = addressNowId;
                        employee.JobTitleId = (Guid)CmbJobTitle.SelectedValue;
                        #endregion
                        #region 试用期的存储数据

                        string dateFormat = string.Format("yyyy年MM月dd日");
                        if (DateBirthDay.SelectedDate != null)
                        {
                            employee.DateOfBirth = (DateTime)DateBirthDay.SelectedDate;


                            var trailDays = new TrailDaysInfoModel();
                            if (DateEntryTime.SelectedDate != null)
                            {
                                trailDays.DateEntryTime = (DateTime)DateEntryTime.SelectedDate;
                                if (DatePositiveTime.SelectedDate != null)
                                {
                                    trailDays.DatePositiveTime = (DateTime)DatePositiveTime.SelectedDate;
                                }
                                else
                                {
                                    MessageBox.Show("转正日期不能空！");
                                }


                            }

                            trailDays.Id = employeeId;
                            trailDays.TrailDays = LabelTrailDays.Text;
                            trailDays.EmployeeEntry = trailDays.DateEntryTime.ToString(dateFormat);
                            trailDays.EmployeePositive = trailDays.DatePositiveTime.ToString(dateFormat);
                            new TrailDaysInfoDAL().InsertTrailDaysInfo(trailDays);
                        }
                        else
                        {
                            MessageBox.Show("出生日期不能为空哦。。");
                            return;
                        }


                        #endregion
                        #region  户籍所在地信息添加
                        var addressDomicile = new EmployeeAddressInfoModel();
                        addressDomicile.Provinces = DomicilebProvList.Text;
                        addressDomicile.City = DomicileCityList.Text;
                        addressDomicile.County = DomicileCountyList.Text;
                        addressDomicile.Address = TxtDomicile.Text;
                        addressDomicile.Category = "户籍所在地";
                        addressDomicile.EmployeeId = employeeId;
                        addressDomicile.AddressAllInfo = DomicilebProvList.Text + DomicileCityList.Text + DomicileCountyList.Text + TxtDomicile.Text;
                        addressDomicile.Id = addressDomicileId;
                        new EmployeeAddressInfoDAL().InsertEmployeeAddressInfo(addressDomicile);
                        //    MessageBox.Show(addressDomicile.AddressAllInfo);
                        #endregion
                        #region 现住址信息添加
                        var addressNow = new EmployeeAddressInfoModel();
                        addressNow.Provinces = NowProvList.Text;
                        addressNow.City = NowCityList.Text;
                        addressNow.County = NowCountyList.Text;
                        addressNow.Address = TxtCurrentAddress.Text;
                        addressNow.EmployeeId = employeeId;
                        addressNow.Category = "现住址";
                        addressNow.Id = addressNowId;
                        addressNow.AddressAllInfo = NowProvList.Text + NowCityList.Text + NowCountyList.Text
                                                    + TxtCurrentAddress.Text;
                        new EmployeeAddressInfoDAL().InsertEmployeeNowAddressInfo(addressNow);
                        #endregion
                        new EmployeeInfoDAL().InsertEmployeeInfo(employee);
                    }
                    #endregion
             
                    else
                        {
                            #region   将文本框中的值传输到model中

                            
                            var employee = new EmployeeInfoModel();
                            EmployeeInfoModel employeeEdit = new EmployeeInfoDAL().GetById(EditGuid);
                         
                            employee.Id = EditGuid;
                            employee.Name = TxtName.Text;
                            employee.Gender = (Guid)CmbSex.SelectedValue;
                            employee.IdCard = TxtIdCards.Text;
                            employee.EducationId = (Guid)CmbEducation.SelectedValue;
                            employee.DepartmentId = (Guid)CmbDepartment.SelectedValue;
                            employee.Post = (Guid)CmbPost.SelectedValue;
                            employee.PoliticalAffiliationId = (Guid)CmbPoliticalAffiliation.SelectedValue;
                            employee.Age = TxtAge.Text;
                            employee.TelePhone = TxtTelephone.Text;
                            employee.EmergencyContact = TxtEmergencyContact.Text;
                            employee.EmergencyContactPhone = TxtEmergencyContactPhone.Text;
                            employee.Nationalities = CmbNation.Text;
                            employee.MaritalStatusId = (Guid)CmbMaritalStatus.SelectedValue;
                            employee.FileNo = TxtFileNo.Text;
                            employee.Email = TxtEmail.Text;
                            employee.Remark = TxtRemarks.Text;
                            employee.TrailDaysId = EditGuid;
                            employee.JobTitleId = (Guid)CmbJobTitle.SelectedValue;
                            employee.DomicileAddressId = employeeEdit.DomicileAddressId;
                            #endregion
                            #region 试用期的存储数据

                            string dateFormat = string.Format("yyyy年MM月dd日");
                            if (DateBirthDay.SelectedDate != null)
                            {
                                employee.DateOfBirth = (DateTime)DateBirthDay.SelectedDate;


                                var trailDays = new TrailDaysInfoModel();
                                if (DateEntryTime.SelectedDate != null)
                                {
                                    trailDays.DateEntryTime = (DateTime)DateEntryTime.SelectedDate;
                                    if (DatePositiveTime.SelectedDate != null)
                                    {
                                        trailDays.DatePositiveTime = (DateTime)DatePositiveTime.SelectedDate;
                                    }
                                    else
                                    {
                                        MessageBox.Show("转正日期不能空！");
                                    }


                                }

                                trailDays.Id = employee.Id;
                                trailDays.TrailDays = LabelTrailDays.Text;
                                trailDays.EmployeeEntry = trailDays.DateEntryTime.ToString(dateFormat);
                                trailDays.EmployeePositive = trailDays.DatePositiveTime.ToString(dateFormat);
                                
                                new TrailDaysInfoDAL().UpdateTrailDaysInfo(trailDays);
                            }
                            else
                            {
                                MessageBox.Show("出生日期不能为空哦。。");
                                return;
                            }


                            #endregion

                             #region  户籍所在地信息添加
                            var addressDomicile = new EmployeeAddressInfoModel();
                            if (DomicilebProvList.Text != null)
                                {
                                    addressDomicile.Provinces = DomicilebProvList.Text;
                                    if (DomicileCityList.Text != null)
                                        {
                                            addressDomicile.City = DomicileCityList.Text;
                                            if (DomicileCountyList.Text != null)
                                                {
                                                    addressDomicile.County = DomicileCountyList.Text;
                                                    if (TxtDomicile.Text != null)
                                                        {
                                                            addressDomicile.Address = TxtDomicile.Text;
                                                            addressDomicile.Category = "户籍所在地";
                                                            addressDomicile.EmployeeId = employee.Id;
                                                            addressDomicile.AddressAllInfo = DomicilebProvList.Text + DomicileCityList.Text + DomicileCountyList.Text + TxtDomicile.Text;
                                                            addressDomicile.Id = employeeEdit.DomicileAddressId;
                                                            new EmployeeAddressInfoDAL().UpdateEmployeeAddressInfo(addressDomicile);
                       
                                                            #endregion
                                                            #region 现住址信息添加
                                                            var addressNow = new EmployeeAddressInfoModel();
                                                            if (NowProvList.Text != null)
                                                                {
                                                                    addressNow.Provinces = NowProvList.Text;
                                                                    if (NowCityList.Text != null)
                                                                        {
                                                                            addressNow.City = NowCityList.Text;
                                                                            if (NowCountyList.Text != null)
                                                                                {
                                                                                    addressNow.County = NowCountyList.Text;
                                                                                    if (TxtCurrentAddress.Text != null)
                                                                                        {
                                                                                            addressNow.Address = TxtCurrentAddress.Text;
                                                                                            addressNow.EmployeeId = employee.Id;
                                                                                            addressNow.Category = "现住址";
                                                                                            addressNow.Id = employeeEdit.CurrentAddressId;
                                                                                            addressNow.AddressAllInfo = NowProvList.Text + NowCityList.Text + NowCountyList.Text
                                                                                                                        + TxtCurrentAddress.Text;
                                                                                        }
                                                                                }
                                                                        }
                                                                }
                                                            new EmployeeAddressInfoDAL().UpdateEmployeeAddressInfo(addressNow);
                                                        }
                                                }
                                        }
                                }
                            else
                                {
                                    MessageBox.Show("籍贯城市有数据为空。请检查");
                                }

                            #endregion

                            new EmployeeInfoDAL().UpdateEmployeeInfo(employee);

                        }

                 

                  //  GridEmployee.DataContext = employee;
      
                    DialogResult = true;

                }

                #region  省市变化的联动

              

                #region 当省市变化的时候，自动加载城市列表

                /// <summary>
                /// 当省市变化的时候，自动加载城市列表
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void DomicilebProvList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
                {
                    if (DomicilebProvList != null)
                        {
                            if (DomicilebProvList.SelectedValue != null)
                                {
                                    int id = (int)DomicilebProvList.SelectedValue;
                                    DomicileCityList.ItemsSource = new AreaFullInfoDAL().GetByAreaFullInfoId(id);
                                }
                        }

                }

                #endregion


                #region  省市地址加载
                
                /// <summary>
                /// 当城市变化的时候，自动加载乡村列表
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
                private void DomicileCityList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
                {
                if (DomicileCityList != null)
                    {
                        if (DomicileCityList.SelectedValue != null)
                            {
                                int id = (int)DomicileCityList.SelectedValue;
                                DomicileCountyList.ItemsSource = new AreaFullInfoDAL().GetByAreaFullInfoId(id);
                            }
                    }

                }

            /// <summary>
                /// 当省市变化的时候，自动加载城市列表
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
                private void NowProvList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
                {

                if (NowProvList.SelectedValue != null)
                    {
                        int id = (int)NowProvList.SelectedValue;
                        NowCityList.ItemsSource = new AreaFullInfoDAL().GetByAreaFullInfoId(id);
                    }


                }

            /// <summary>
                /// 当城市变化的时候，自动加载乡村列表
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
                private void NowCityList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
                {

                if (NowCityList.SelectedValue != null)
                    {
                        int id = (int)NowCityList.SelectedValue;
                        NowCountyList.ItemsSource = new AreaFullInfoDAL().GetByAreaFullInfoId(id);
                    }


                }
                #endregion
                #endregion


                /// <summary>
            /// 当入职时间变化时
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
                private void DateEntryTime_SelectedDateChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
            {
                if (IsInsert)
                    {
                         if (DateEntryTime.SelectedDate != null)
                    {
                        DateTime oop=(DateTime)DateEntryTime.SelectedDate;
                        DateTime ooTime = oop.AddMonths(3);

                        DatePositiveTime.SelectedDate = ooTime.AddDays(-1);
                    }

                    }
               
            

            }

                private void DatePositiveTime_SelectedDateChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
                {
                   
                                  if (DatePositiveTime.SelectedDate != null)
                        {
                            if (DateEntryTime.SelectedDate != null)
                                {
                                    TimeSpan span = (DateTime)DatePositiveTime.SelectedDate - (DateTime)DateEntryTime.SelectedDate;
                                    double days = span.Days;
                                double months=    days/30;
                                    if (months<=0)
                                        {
                                            MessageBox.Show("试用期天数不正确，请检查");
                                        }
                                    LabelTrailDays.Text = months + "月";
                                }
                        }
                        

              
                    

                 
                }

            }
    }